package com.kinglone.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kinglone.util.PropertieUtil;
import com.kinglone.util.ResultMsg;
/**
 * 下载
 * @author Administrator
 *
 */
@Controller
public class DownloadController {
	
	
	@RequestMapping("/test/download.jspx")
	public void download(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String fileName = request.getParameter("fileName");
		String fileUrl = request.getParameter("fileUrl");
		/*  File file = new File(fileUrl);
		PrintWriter p = response.getWriter();
		 if(!file.exists()){			 
			p.write("您要下载的资源已被删除！");			
			return;
		}*/
		 
		//第一步：设置响应类型
		 response.setContentType("application/force-download");//应用程序强制下载
	    //第二读取文件
		//上传文件路径
  	   	String basepath=PropertieUtil.getValue("config.properties", "upload_url");
  	   	String holePath=basepath+fileUrl;
  	   	System.out.println("完整存储路径："+holePath);
	    InputStream in = new FileInputStream(holePath);
	    //设置响应头，对文件进行url编码
	    fileName = URLEncoder.encode(fileName, "UTF-8");
	    response.setHeader("Content-Disposition", "attachment;filename="+fileName);   
	    response.setContentLength(in.available());
	    
	    //第三步：老套路，开始copy
	    OutputStream out = response.getOutputStream();
	    byte[] b = new byte[1024];
	    int len = 0;
	    while((len = in.read(b))!=-1){
	      out.write(b, 0, len);
	    }
	    out.flush();
	    out.close();
	    in.close();
	 }

	
	/**
	 * 描述：客户端根据地址下载对应任务
	 * @param request
	 * @throws Exception 
	 */
	@RequestMapping("/downLoad")
	@ResponseBody
	public ResultMsg downLoad(HttpServletRequest request,HttpServletResponse response,@RequestParam String taskId,@RequestParam String impName) throws Exception{
		ResultMsg msg=new ResultMsg();	
		/*String uaddr = request.getRemoteAddr();
		
		List<String> list = null;
		List<String> list = tPubCodeValueService.findIPByClassNo("17");
		if(!list.contains(uaddr)){
			msg.setMessage("该IP地址无下载权限!");
			msg.setResultCode("-1");
			msg.setSuccess(false);
			return msg;
		}	*/	

		Map<String,Object> mapParam = new HashMap<String,Object>();
		mapParam.put("taskId", taskId);
		mapParam.put("impName", impName);
		String dir = "";
		//String dir = importPdfService.findDir(mapParam);
		System.out.println("dir:"+dir);
		String basepath=PropertieUtil.getValue("config.properties", "upload_url");
		String url = basepath+dir;
		String fileName = url.substring(url.lastIndexOf("/")+1);
		fileName = URLEncoder.encode(fileName, "UTF-8");
	    InputStream in = new FileInputStream(url);
	    // 设置输出的格式
	    response.setContentType("application/force-download");
	    response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
	    response.setContentLength(in.available());
	    OutputStream out = response.getOutputStream();
	    // 循环取出流中的数据
	    byte[] b = new byte[4096];
	    int len = 0;
	    try {
	      while ((len = in.read(b)) > 0){
	    	  out.write(b, 0, len);  
	      }    	  
	    	  out.flush();
	    	  out.close();
	    	  in.close();
	    	
	      	msg.setResultCode("0");
			msg.setSuccess(true);
	    } catch (Exception e) {
	      e.printStackTrace();
	      msg.setMessage("下载失败!");
			msg.setResultCode("-1");
			msg.setSuccess(false);
		}
		return msg;
	}	
	/*@RequestMapping("/downLoad2")
	@ResponseBody
	public ResultMsg downLoad2(HttpServletRequest request,HttpServletResponse response,@RequestParam String taskId,@RequestParam String impName) throws Exception{
		ResultMsg msg=new ResultMsg();	
		String url="http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg";
		String fileName = url.substring(url.lastIndexOf("/"));
		String fileDir = "D:";
		String filePath = fileDir+"/downLoad";
		
		File file = new File(filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.connect();
			InputStream inputStream = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(inputStream);
			if (!filePath.endsWith("/")) {  			  
	             filePath += "/";  	  
	         } 
			FileOutputStream fileOut = new FileOutputStream(filePath +fileName);
			BufferedOutputStream bos = new BufferedOutputStream(fileOut);
			byte[] by = new byte[4096];
			int len = bis.read(by);
			while(len != -1){
				bos.write(by, 0, len);
				len = bis.read(by);
			}
			bos.close();  
	        bis.close();  
	        conn.disconnect();
	        msg.setResultCode("0");
			msg.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setMessage("下载失败!");
			msg.setResultCode("-1");
			msg.setSuccess(false);
		}
		return msg;
	}	*/
}
